#!/usr/bin/perl

#############################################################################
# File: execAssm.pl
#
# Soderlund Lab, University of Arizona, 2010
#
# Do a TCW assembly. 
# Uses a Java module, for which maximum memory must first be set. 
#
#############################################################################


# Maximum memory to use, in megabytes.
# If zero, it will be automatically calculated based on the
# size of the project.
# In order to use more than 2Gb, you must be using 64-bit Java. 
my $maxmem = 50000;

use warnings;
use strict;
$| = 1;
use DBI;
use Cwd;
use Cwd 'abs_path';
use File::Path;
use lib 'scripts';
use shared;

# Check that runPAVE is run from top level only

my $PROJECTS_DIR = 'projects';

if (not -d $PROJECTS_DIR )
{
	die "Please run execAssm.pl from the top level sTCW directory only\n";
}

my %Params;  #values from configuration files
our $PAVEcfg = 'sTCW.cfg'; 
my $project_name = ''; 

#############################################################
# Get command-line parameters
if (0 == scalar @ARGV || $ARGV[0] =~ /^help$/i) {
	print "\nUsage: execAssm.pl [-q] <directory> [sTCW.cfg]\n";
	print "	<directory> must be under /projects.\n";
	print "Run the assembly specified in <directory>/sTCW.cfg.\n";
	print "Optional -q runs without prompting.\n";
	exit;
}

my $argStart = 0;
if ($ARGV[0] eq "-q") 
{
	$argStart = 1;
}
$project_name = $ARGV[$argStart];

if (1 + $argStart < scalar @ARGV) {
	$PAVEcfg = $ARGV[1 + $argStart];
}

$PAVEcfg = "$PROJECTS_DIR/$project_name/$PAVEcfg";
die "Config file $PAVEcfg does not exist.\n" unless -f $PAVEcfg;
my $HOSTScfg = "HOSTS.cfg";

readCfgFile($PAVEcfg,\%Params);
if (not defined $Params{AssemblyID})
{
	die "Config file missing AssemblyID\n";
}
if (not defined $Params{PAVE_db})
{
	die "Config file missing PAVE_db\n";
}
my $AssemblyID = $Params{AssemblyID}; 
my $PAVE_db = $Params{PAVE_db};

completeDBParams(\%Params,$HOSTScfg);


# PAVE database parameters

my $PAVE_usr = $Params{PAVE_user} || "";
my $PAVE_host = $Params{PAVE_host} || "";
my $PAVE_password = $Params{PAVE_password} || "";
#Make sure PAVE DB is there 
my $dbh = DBI->connect( "dbi:mysql:$PAVE_db;host=$PAVE_host", "$PAVE_usr", "$PAVE_password",{ PrintError => 0} ) 
		or die "*** could not locate database $PAVE_db on $PAVE_host (are the DB parameters in HOSTS.cfg correct?).\n";  

my $exists = 0;
my $sqlCheck = qq{select assemblyid from assembly where assemblyid = ?};
my $sthCheck = $dbh->prepare($sqlCheck);
$sthCheck->execute( $AssemblyID );
$sthCheck->bind_columns( \$exists );
$sthCheck->fetch;
$sthCheck->finish;

if ($maxmem == 0)
{

    my $sth = $dbh->prepare("select count(*) from clone");
    $sth->execute();
    ((my $numClones) = $sth->fetchrow_array());

    $sth = $dbh->prepare("select sum(libsize*avglen)/sum(libsize) from library");
    $sth->execute();
    ((my $avgLen) = $sth->fetchrow_array());

	$maxmem = int($numClones/200);
	if ($avgLen > 300)
	{
		my $lenfact = $avgLen/300;
		$maxmem = int($maxmem*$lenfact);
	}
   $maxmem += 1000; 
   if ($numClones > 3000000)
	{
		print "*Warning: $numClones EST found in database. Estimated memory requirement: $maxmem"."M".".\n" ;
		print "*See System Guide for more information on memory usage.\n" ;
		sleep(2);
	} 
    print "Memory set to $maxmem\n";
	$ENV{"PAVE_MEM"} = $maxmem;
}

my $jardir = "java/jars";
my $jar = "$jardir/stcw.jar";

if (not -f $jar)
{
	die "can't find $jar; make sure to run from the pave_2_0 directory.\n";
}

my $classpath = "$jar:$jardir/mysql-connector-java-5.0.5-bin.jar";
my $cmd = "java -Xmx${maxmem}m -cp $classpath assem.AssemMain ".join(" ",@ARGV);

print "Command".$cmd;
system($cmd);


